package com.innovation.ic.cyz.admin.controller;

import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.cyz.admin.thread.SendUpdateOrderStatusMqMsgToHqThread;
import com.innovation.ic.cyz.base.model.cyz.RepairOrder;
import com.innovation.ic.cyz.base.pojo.enums.RepairOrderSourceEnum;
import com.innovation.ic.cyz.base.pojo.global.ApiResult;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.variable.cyz.repair_order.RepairOrderAdminListRespPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.repair_order.RepairOrderInfoRespPojo;
import com.innovation.ic.cyz.base.vo.cyz.repairOrder.RepairOrderQueryListVo;
import com.innovation.ic.cyz.base.vo.cyz.repairOrder.RepairOrderReplyVo;
import com.innovation.ic.cyz.base.vo.cyz.repairOrder.RepairOrderSolveVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

@Api(value = "工单API", tags = "RepairOrderController")
@RestController
@RequestMapping("/api/v1/repairOrder")
public class RepairOrderController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(RepairOrderController.class);

    /**
     * 工单列表查询
     */
    @ApiOperation(value = "工单列表查询")
    @ApiImplicitParam(name = "RepairOrderQueryListVo", value = "工单列表查询的vo类", required = true, dataType = "RepairOrderQueryListVo")
    @RequestMapping(value = "/queryList", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<RepairOrderAdminListRespPojo>> add(@RequestBody RepairOrderQueryListVo repairOrderQueryListVo, HttpServletRequest request, HttpServletResponse response) {
        ServiceResult<RepairOrderAdminListRespPojo> result = repairOrderService.queryRepairOrderList(repairOrderQueryListVo);

        ApiResult<RepairOrderAdminListRespPojo> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(result.getResult());
        apiResult.setMessage(ServiceResult.INSERT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 根据工单id获取工单内容
     */
    @ApiOperation(value = "根据工单id获取工单内容")
    @ApiImplicitParam(name = "id", value = "工单id", dataType = "Long", required = true)
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<RepairOrderInfoRespPojo>> info(@PathVariable("id")Long id, HttpServletRequest request, HttpServletResponse response) {
        if (id == null) {
            String message = "调用接口[/api/v1/repairOrder/info]时，参数id不能为空";
            log.warn(message);
            ApiResult<RepairOrderInfoRespPojo> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<RepairOrderInfoRespPojo> result = repairOrderService.getRepairOrderInfoById(id);

        ApiResult<RepairOrderInfoRespPojo> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(result.getResult());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 工单回复
     */
    @ApiOperation(value = "工单回复")
    @ApiImplicitParam(name = "RepairOrderReplyVo", value = "工单回复的vo类", required = true, dataType = "RepairOrderReplyVo")
    @RequestMapping(value = "/reply", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> reply(@RequestBody RepairOrderReplyVo repairOrderReplyVo, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        if (repairOrderReplyVo.getId() == null) {
            String message = "调用接口[/api/v1/repairOrder/reply]时，参数id不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        if(!StringUtils.validateParameter(repairOrderReplyVo.getDescribe()) && (repairOrderReplyVo.getFileUrls() == null || repairOrderReplyVo.getFileUrls().size() == 0)){
            String message = "调用接口[/api/v1/repairOrder/reply]时，参数describe、fileUrls不能同时为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<Boolean> result = repairOrderService.replyRepairOrder(repairOrderReplyVo, this.getUserInfo(request), null);

        if(result.getResult()){
            // 推送rabbitmq消息到虎趣
            sendRabbitMqMsgToHq(repairOrderReplyVo.getId());
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(result.getResult());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 工单解决
     */
    @ApiOperation(value = "工单解决")
    @ApiImplicitParam(name = "RepairOrderSolveVo", value = "工单解决的vo类", required = true, dataType = "RepairOrderSolveVo")
    @RequestMapping(value = "/solve", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> solve(@RequestBody RepairOrderSolveVo repairOrderSolveVo, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        if (repairOrderSolveVo.getId() == null || repairOrderSolveVo.getSolvePlan() == null) {
            String message = "调用接口[/api/v1/repairOrder/solve]时，参数id、solvePlan不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<Boolean> result = repairOrderService.solveRepairOrder(repairOrderSolveVo, this.getUserInfo(request));

        if(result.getResult()){
            // 推送rabbitmq消息到虎趣
            sendRabbitMqMsgToHq(repairOrderSolveVo.getId());
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(result.getResult());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 工单指派
     */
    @ApiOperation(value = "工单指派")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "工单id", dataType = "Long", required = true),
            @ApiImplicitParam(name = "headId", value = "FAE的id", dataType = "Long", required = true)
    })
    @RequestMapping(value = "/assign/{orderId}/{headId}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> assign(@PathVariable("orderId") Long orderId, @PathVariable("headId") Long headId, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        if (orderId == null || headId == null) {
            String message = "调用接口[/api/v1/repairOrder/assign]时，参数orderId、headId不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<Boolean> result = repairOrderService.assign(orderId, headId, this.getUserInfo(request));

        if(result.getResult()){
            // 推送rabbitmq消息到虎趣
            sendRabbitMqMsgToHq(orderId);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(result.getResult());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 推送rabbitmq消息到虎趣
     * @param orderId 工单id
     */
    private void sendRabbitMqMsgToHq(Long orderId){
        // 根据id获取工单信息
        ServiceResult<RepairOrder> serviceResult = repairOrderService.selectById(orderId);
        if(serviceResult.getResult() != null && RepairOrderSourceEnum.HQ.getCode().equals(serviceResult.getResult().getSource())){
            // 推送mq消息到虎趣更新工单状态信息
            SendUpdateOrderStatusMqMsgToHqThread sendUpdateOrderStatusMqMsgToHqThread = new SendUpdateOrderStatusMqMsgToHqThread(rabbitMqParamConfig, serviceHelper, repairOrderRecordService, repairOrderFileService, serviceResult.getResult());
            threadPoolManager.execute(sendUpdateOrderStatusMqMsgToHqThread);
        }
    }
}